﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Routing;
using System.Web.Security;
using Teamwish.Domain.Common;
using Teamwish.Domain.Models;
using Teamwish.Utilities;
using Teamwish.Webapi.Models;

namespace Teamwish.Webapi.Filters
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class RedisTokenAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            bool skipAnonymous = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0 || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0;           
            //不跳过处理验证
           if (!skipAnonymous)
            {
                 //从请求头中获取token
                var authorization = actionContext.Request.Headers.Authorization;
                if (authorization != null && authorization.Parameter != null)
                {
                    //header中获取token 
                    string[] sendToken = authorization.Parameter.Split('_');
                    if (sendToken.Length != 3|| !CommonHelper.IsInt(sendToken[0]))
                    {
                        Throw401Exception(actionContext, "权限头设置有问题");
                        return;
                    }
                    string deviceType = sendToken[1];
                    int userid = int.Parse(sendToken[0]);
                    string token = Redis.RedisHelper.Get<string>("token_"+ deviceType + "_"+ userid);
                 
                    if (string.IsNullOrWhiteSpace(token))
                    {
                        Throw401Exception(actionContext,"token不正确或者过期了");
                        return;
                    }
                    if (token != sendToken[2])
                    {
                        Throw401Exception(actionContext, "token无效");
                        return;
                    }
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);

                }               
               
            }


        }
        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {         
            var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            var content = new SeverMsg
            {
                status = -1,
                message = "未授权"
            };
            response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");
        }

        private static void Throw401Exception(HttpActionContext actionContext, string exceptionString)
        {
                    
            var response = actionContext.Response = actionContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            var content = new SeverMsg
            {
                status = -1,
                message = exceptionString ?? "未授权"
            };
            
            response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");

        }
    }
}